package com.lijunjie.platform.api.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lijunjie.platform.api.modules.sys.entity.User;
import com.lijunjie.platform.api.modules.sys.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

public class UserRealm extends AuthorizingRealm {

    private static Logger logger = LoggerFactory.getLogger(UserRealm.class);

    private String name = "LoginRealm";

    @Resource
    private IUserService userService;

    @Override
    public void setName(String name) {
        name = this.name;
        super.setName(name);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info("loginRealm doGetAuthenticationInfo");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username).eq("is_enabled",1);
        User user = userService.getOne(queryWrapper);
        if(null == user){
            throw new UnknownAccountException("用户不存在！");
        }
        if(user.getIsLocked()){
            throw new LockedAccountException("账户锁定！");
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),
                this.getName());
        return simpleAuthenticationInfo;
    }
}
